
class Solution25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        int len = size(head) ;
        return dg(head  , len, k) ;
    }
    private ListNode dg(ListNode head ,int len , int k){
        if(len < k) return head ;
        if(head == null) return null ;
        int tmp = k ;
        ListNode newHead = head ;
        ListNode last = newHead ;
        ListNode cur = head.next ;
        ListNode nextDg = cur ;
        while(cur != null && k > 1){
            ListNode curNext = cur.next ;
            cur.next = newHead ;
            newHead = cur ;
            cur = curNext ;
            k -- ;
            nextDg = curNext ;
        }
        last.next = dg(nextDg ,len-tmp , tmp) ;
        return newHead ;
    }
    private int size(ListNode head){
        if(head == null) return 0 ;
        int sum = 0 ;
        ListNode cur = head ;
        while(cur != null){
            sum ++ ;
            cur = cur.next ;
        }
        return sum ;
    }

   static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

}
